package com.aboo.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * IP工具箱
 * @author Yata
 *
 */
public class IPUtils {
	
	private static Logger logger = Logger.getLogger(IPUtils.class);

	/**
	 * 获取本机所有的InetAddress对象
	 * @return
	 */
	public static List<InetAddress> getAllHostInetAddress() {
		try {
			List<InetAddress> result = null;
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

			if (networkInterfaces != null) {
				result = new ArrayList<InetAddress>();
				while (networkInterfaces.hasMoreElements()) {
					NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
					Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
					while (inetAddresses.hasMoreElements()) {
						InetAddress inetAddress = inetAddresses.nextElement();
						result.add(inetAddress);
					}
				}
			}			

			return result;
		} catch (SocketException se) {
			throw new RuntimeException(se.getMessage(), se);
		}
	}

	/**
	 * 获取所有非回送地址
	 * @return
	 */
	public static List<String> getAllNoLoopbackHostAddress() {
		List<String> noLoopbackAddresses = null;
		List<InetAddress> allInetAddresses = getAllHostInetAddress();

		if (allInetAddresses != null) {
			noLoopbackAddresses = new ArrayList<String>();
			
			for (InetAddress inetAddress : allInetAddresses) {
				if (!inetAddress.isLoopbackAddress()) {
					noLoopbackAddresses.add(inetAddress.getHostAddress());
				}
			}
		}
		
		return noLoopbackAddresses;
	}
	
	/**
	 * 获取所有地址
	 * @return
	 */
	public static List<String> getAllHostAddress() {
		List<String> noLoopbackAddresses = null;
		List<InetAddress> allInetAddresses = getAllHostInetAddress();

		if (allInetAddresses != null) {
			noLoopbackAddresses = new ArrayList<String>();
			
			for (InetAddress inetAddress : allInetAddresses) {
				noLoopbackAddresses.add(inetAddress.getHostAddress());
			}
		}
		
		return noLoopbackAddresses;
	}

	/**
	 * 获取第一个非回送IP地址
	 * @return
	 */
	public static String getFirstNoLoopbackIPAddress() {
		String address = "";
		List<String> allNoLoopbackAddresses = getAllNoLoopbackHostAddress();
		if (allNoLoopbackAddresses != null && allNoLoopbackAddresses.size() > 0) {
			address = (String) allNoLoopbackAddresses.get(0);
		}
		
		return address;
	}
	
}
